package com.greatchn.authorization_server.web.srv;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.greatchn.authorization_server.util.ServiceAssert;
import com.greatchn.authorization_server.web.dao.IOauthRoleGroupInfoDao;
import com.greatchn.authorization_server.web.dao.IOauthUserInfoDao;
import com.greatchn.authorization_server.web.po.OauthRoleGroupInfo;
import com.greatchn.authorization_server.web.po.OauthUserInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @OauthUserInfoSrv: OauthUserInfo srv
 * @author: ZBoHang
 * @time: 2023/2/28 9:27
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OauthUserInfoSrv {

    @Resource
    private IOauthUserInfoDao iOauthUserInfoDao;
    @Resource
    private IOauthRoleGroupInfoDao iOauthRoleGroupInfoDao;

    /**
     * get function by username
     */
    public Set<String> getRoleNameByUserName(String userName) {

        OauthUserInfo oauthUserInfo = this.getByUserName(userName);
        ServiceAssert.notNull(oauthUserInfo, "用户不存在!");

        Set<String> roleStrSet = new HashSet<>(12);
        // 所属用户组
        List<Integer> userGroupIdList =
                StrUtil.split(oauthUserInfo.getBelongToUserGroup(), StrUtil.COMMA).stream()
                        .map(Integer::valueOf).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(userGroupIdList)) {
            // 用户组对应的所有角色
            List<OauthRoleGroupInfo> roleGroupInfo = this.iOauthRoleGroupInfoDao.findByBelongToUserGroupIdIn(userGroupIdList);
            roleGroupInfo.stream().map(OauthRoleGroupInfo::getRoleGroupName).forEach(roleStrSet::add);
        }
        // 所属角色组
        List<Integer> roleGroupIdList =
                StrUtil.split(oauthUserInfo.getBelongToRoleGroup(), StrUtil.COMMA).stream()
                        .map(Integer::valueOf).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(roleGroupIdList)) {
            // 角色组对应角色
            List<OauthRoleGroupInfo> roleGroupInfo = this.iOauthRoleGroupInfoDao.findByRoleGroupIdIn(roleGroupIdList);
            roleGroupInfo.stream().map(OauthRoleGroupInfo::getRoleGroupName).forEach(roleStrSet::add);
        }

        ServiceAssert.isFalse(CollUtil.isEmpty(roleStrSet), "用户权限异常!");
        return roleStrSet;
    }

    /**
     * get by username
     */
    public OauthUserInfo getByUserName(String userName) {

        return this.iOauthUserInfoDao.getOne(userName);
    }
}
